
const { User } = require("../db");
const jwt = require('jsonwebtoken');
const { secretKey } = require('../config/config');
const { Op, Sequelize } = require('sequelize');
const multer = require('multer');
const xlsx = require('xlsx');

exports.login = async (req, res) => {
    const { username, password } = req.body
    if (username && password) {
        try {
            const tempUser = await User.findOne({ where: { username: username } });
            if (tempUser) {
                if (tempUser.dataValues.password === password) {
                    const tokenStr = jwt.sign({ id: tempUser.dataValues.id }, secretKey, { expiresIn: '86400s' }) // jwt过期时间设置为一天
                    res.send({
                        status: 200,
                        message: '登录成功！',
                        user: { ...tempUser.dataValues },
                        token: tokenStr, 
                    })
                }
                else {
                    res.send({
                        status: 500,
                        message: '密码错误！'
                    })
                }
            }
            else {
                res.send({
                    status: 404,
                    message: '用户不存在！'
                })
            }
        }
        catch (err) {
            console.log(err);
            res.status(500).send('Failed to login');
        }
    }
}

//新建账户
exports.register = async (req, res) => {
    const { username, password, role } = req.body
    if (username && password) {
        try {
            const tempUser = await User.findOne({ where: { username: username } });
            if (tempUser) {
                res.send({
                    status: 304,
                    message: '用户已存在！'
                })
            } else {
                const newUser = await User.create({
                    username: username,
                    password: password,
                    // jobNumber: jobNumber,
                    role: role,
                    // name: name
                })
                if (newUser) {
                    res.send({
                        status: 200,
                        message: '注册成功！',
                    })
                }
                else {
                    res.send({
                        status: 500,
                        message: '注册失败！',
                    })
                }
            }
        } catch (err) {
            console.log(err);
            res.status(500).send('Failed to register');
        }
    }
}


exports.getAllUsers = async (req, res) => {
    try {
        const { username = '', role = '', page = 1, pageSize = 10 } = req.body;
        console.log(username, role, page, pageSize);

        const users = await User.findAndCountAll({
            where: {
                // name: {
                //     [Op.like]: `%${name}%`
                // },
                username: {
                    [Op.like]: `%${username}%`
                },
                role: {
                    [Op.like]: `%${role}%`
                },
                // jobNumber: {
                //     [Op.like]: `%${jobNumber}%`
                // }
            },
            offset: (page - 1) * pageSize,
            limit: pageSize,
            order: [
                // 保证中文排序正确不乱序
                [Sequelize.literal("CONVERT(username USING gbk)"), "ASC"]
            ]
        })
        res.send({
            status: 200,
            message: '获取用户列表成功！',
            users: users.rows,
            total: users.count
        })
    }
    catch (err) {
        console.log(err);
        res.status(500).send('Failed to get all users');
    }
}

exports.deleteUser = async (req, res) => {
    const { id } = req.body
    try {
        const user = await User.destroy({
            where: {
                id: id
            }
        })
        if (user) {
            res.send({
                status: 200,
                message: '删除用户成功！',
            })
        }
        else {
            res.send({

            })
        }
    }
    catch (err) {
        console.log(err);
        res.status(500).send('Failed to delete user');
    }
}

exports.updateUser = async (req, res) => {
    const { id, username, password, role,  } = req.body
    try {
        const user = await User.update({
            username: username,
            password: password,
            // jobNumber: jobNumber,
            role: role,
            // name: name
        }, {
            where: {
                id: id
            }
        })
        if (user) {
            res.send({
                status: 200,
                message: '更新用户成功！',
            })
        }
        else {
            res.send({
                status: 500,
                message: '更新用户失败！',
            })
        }
    } catch (err) {
        console.log(err);
        res.status(500).send('更新用户失败');
    }
}

// 处理 Excel 文件导入的函数
exports.uploadXlsxUsers = async (req, res) => {
    try {
        console.log(req.file); // 打印文件信息
        const workbook = xlsx.readFile(req.file.path);
        const sheetName = workbook.SheetNames[0];
        const data = xlsx.utils.sheet_to_json(workbook.Sheets[sheetName]);
        
        for (const user of data) {
            // 假设 Excel 文件中的列名与数据库字段名一致
            // 校验 username 是否存在
            const userExist = await User.findOne({
                where: {
                    username: user.username
                }
            })
            if (userExist) {
                res.status(500).send({
                    status: 500,
                    message: '导入失败！工号不可重复!',
                })
                return
            }
            else {
                await User.create({
                    // jobNumber: user.jobNumber,
                    username: user.username,
                    // name: user.name,
                    role: user.role,
                    password: user.password
                });
            }
        }
        res.send({
            status: 200,
            message: '用户信息导入成功！'
        });
    } catch (error) {
        console.log(error);
        res.status(500).send('Failed to import users');
    }
};

// 根据旧密码修改密码
exports.updatePassword = async (req, res) => {
    const { password, oldPassword } = req.body
    console.log(password, oldPassword);
    
    const { id: userId } = req.user
    try {
        const user = await User.findOne({
            where: {
                id: userId
            }
        })
        if (user.dataValues.password === oldPassword) {
            await User.update({
                password: password
            }, {
                where: {
                    id: userId
                }
            })
            res.send({
                status: 200,
                message: '修改密码成功！',
            })
        }
        else {
            res.send({
                status: 500,
                message: '密码错误！',
            })
        }
    } catch (err) {
        console.log(err);
        res.status(500).send('修改密码失败');
    }
}